/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head)
    {
        map<Node*, Node*> m;
        Node* cur = head, * copyhead = nullptr, * copytail = nullptr;
        while (cur)
        {
            if (copyhead == nullptr)
            {
                copyhead = copytail = new Node(cur->val);
            }
            else
            {
                copytail->next = new Node(cur->val);
                copytail = copytail->next;
            }

            m[cur] = copytail;
            cur = cur->next;
        }

        cur = head;
        Node* copy = copyhead;
        while (copy)
        {
            if (cur->random == nullptr)
            {
                copy->random = nullptr;
            }
            else
            {
                copy->random = m[cur->random];
            }
            copy = copy->next;
            cur = cur->next;
        }
        return copyhead;
    }
};